package com.tos.second.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tos.second.common.basecontext.BaseContext;
import com.tos.second.common.exception.BaseException;
import com.tos.second.entity.Goods;
import com.tos.second.entity.Orders;
import com.tos.second.mapper.GoodsMapper;
import com.tos.second.mapper.OrdersMapper;
import com.tos.second.service.GoodsService;
import com.tos.second.service.OrdersService;
import com.tos.second.vo.OrdersHistoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {


    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 获取用户历史订单
     *
     * @return
     */
    @Override
    public List<OrdersHistoryVo> getOrdersHistory() {
        // 获取当前登录用户的id
        Long currentId = BaseContext.getCurrentId();
        //创造查询条件
//        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Orders::getBuyerId, currentId);
        //获取用户历史订单
        List<Orders> list = ordersMapper.getMyBuyList(currentId);
        //进行stream流创造
        return list.stream().map(item -> {
            OrdersHistoryVo ordersHistoryVo = new OrdersHistoryVo();
            //复制基本相同属性
            BeanUtils.copyProperties(item, ordersHistoryVo);
            //查询其他数据，根据goodsId查询
            Long goodsId = item.getGoodsId();
            Goods byId = goodsMapper.getGoodsById(goodsId);
            if (byId == null) {
                ordersHistoryVo.setGoodsName(null);
                ordersHistoryVo.setImage(null);
                ordersHistoryVo.setGoodsDescription(null);
            }
            //赋值属性
            else {
                ordersHistoryVo.setGoodsName(byId.getName());
                ordersHistoryVo.setImage(byId.getImage());
                ordersHistoryVo.setGoodsDescription(byId.getDescription());
            }
            return ordersHistoryVo;
        }).toList();
    }
}
